package com.example.sdcarddemo;

import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

public class MainActivity extends AppCompatActivity {
    TextView tv1,tv2;
    Button bt1,bt2;
    private static String randomNumStr="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = findViewById(R.id.textView);
        tv2=findViewById(R.id.textView2);
        bt1=findViewById(R.id.button);
        bt2=findViewById(R.id.button2);
        bt1.setOnClickListener((v)->{
            for (int i = 0; i <10 ; i++) {
                randomNumStr+=(int)(Math.random()*10000+1)+"\n";
                tv2.setText(randomNumStr);
            }
        });
        bt2.setOnClickListener((v)->{
            File file = new File("/sdcard/");
            String fileName= System.currentTimeMillis()+"txt";
            if (file.exists()&&file.canWrite()) {
                File newFile=new File(file.getAbsolutePath()+File.pathSeparator+fileName);
                FileOutputStream fileOutputStream=null;
                try{
                    if(newFile.createNewFile()){
                        fileOutputStream=new FileOutputStream(file);
                        fileOutputStream.write(randomNumStr.getBytes());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}